package cn.miaoyao.miaoyaoms.config;
import cn.miaoyao.miaoyaoms.Handler.AccessPageIntercepter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @Author: shushu
 * @Date: 2023/03/28/14:37
 * @Description:springmvc的配置。
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 将login.html页面从templates页面下放行。
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login.html");
        registry.addViewController("/index.html");
        registry.addViewController("/page/*.html");
    }
    //配置json转换器替换原始默认的
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建一个新的转换器添加到converters中（fastjson转换器）
        FastJsonHttpMessageConverter messageConverter=new FastJsonHttpMessageConverter();
        //创建为转换器配置转换规则的对象
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.QuoteFieldNames,//输出key的时候是否使用双引号，默认false
                SerializerFeature.WriteDateUseDateFormat,//实现日期格式化。
                SerializerFeature.DisableCircularReferenceDetect//消除对同一个对象循环引用的问题
        );
        //配置日期的转换规则
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置字符编码转换规则
        fastJsonConfig.setCharset(Charset.forName("utf-8"));
        //为转换器设置转换规则
        messageConverter.setFastJsonConfig(fastJsonConfig);
        //将转换器添加到converters
        converters.add(messageConverter);
    }

    /**
     * 将拦截器加载到ioc容器中
     * @return
     */
    @Bean
    public AccessPageIntercepter getIntercepter(){
        return new AccessPageIntercepter();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getIntercepter()).addPathPatterns("/index.html");
        registry.addInterceptor((getIntercepter())).addPathPatterns("/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //访问的路径，当访问/uploadImage的时候，会找locations的路径文件上找
        registry.addResourceHandler("/uploadImage").addResourceLocations("file:D:/IDEA/miaoyaoms/target/classes/static/upload/");
    }
}
